<?php

namespace CuiFox\yii\components;

use Yii;
use yii\base\Component;
use yii\base\Event;
use yii\web\Response;
use yii\web\View;
use CuiFox\yii\helpers\CompressorHelper;

/**
 * Class Compressor
 * @package CuiFox\yii\components
 * ```
 * 'bootstrap'  => ['compressor'],
 * 'components' => [
 *      ...
 *      'compressor' => [
 *          'class' => 'CuiFox\yii\components\Compressor',
 *          'html' => true,
 *          'css' => true,
 *          'js' => true,
 *      ],
 * ],
 * ```
 */
class Compressor extends Component
{
    /**
     * Compress html. Process before response send
     * @var bool
     */
    public $html = false;
    /**
     * Compress css on page, added by registerCss. Process before render page in view component
     * @var bool
     */
    public $css = false;
    /**
     * Compress css on page. Process before render page in view component
     * @var bool
     */
    public $js = false;
    /**
     * Response formats list, where enable compress html
     * @var array
     */
    public $formats = [
        Response::FORMAT_HTML,
    ];

    /**
     * Init
     */
    public function init()
    {
        /** @var $this View */
        Yii::$app->view->on(View::EVENT_END_PAGE, [$this, 'onEventEndPage']);
        Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'onEventBeforeSend']);
    }

    /**
     * @param Event $event
     */
    public function onEventEndPage(Event $event)
    {
        $view = $event->sender;

        if ($this->css && !empty($view->css)) {
            foreach ($view->css as &$css) {
                $css = CompressorHelper::css($css);
            }
        }
        if ($this->js && !empty($view->js)) {
            foreach ($view->js as &$list) {
                foreach ($list as &$js) {
                    $js = CompressorHelper::js($js);
                }
            }
        }
    }

    /**
     * @param Event $event
     */
    public function onEventBeforeSend(Event $event)
    {
        $response = $event->sender;

        if ($this->html & in_array($response->format, $this->formats)) {
            if (!empty($response->data)) {
                $response->data = CompressorHelper::html($response->data);
            }
            if (!empty($response->content)) {
                $response->content = CompressorHelper::html($response->content);
            }
        }
    }
}